// #include <unistd.h>
// #include <stdlib.h>
#include <linux/spi/spi.h>
#include <linux/delay.h>
#include <linux/gpio.h>

#include "GC9A01.h"
#include "spi_screen_driver.h"

#define PIN_RST     36//5
#define PIN_DC      47//17	
#define PIN_CS		44//15			
#define PIN_BL		62//2		

#define TX_MAX_LEN 4096  

// Hardware abstraction layer
// Should be defined by the user of the library

void GC9A01_init_hard(void) {


    int ret = 0;
    ret = gpio_request(PIN_RST, "PIN_RST");
    if (ret < 0)
    {
        printk("gpio_request:PIN_RST err\n");
    }

    ret = gpio_request(PIN_DC, "PIN_DC");
    if (ret < 0)
    {
        printk("gpio_request:PIN_DC err\n");
    }

    ret = gpio_request(PIN_BL, "PIN_BL");
    if (ret < 0)
    {
        printk("gpio_request:PIN_BL err\n");
    }


    ret = gpio_direction_output(PIN_RST, 0);
    if (ret < 0)
    {
        printk("gpio_direction_output:PIN_RST err\n");
    }
    ret = gpio_direction_output(PIN_DC, 0);
    if (ret < 0)
    {
        printk("gpio_direction_output:PIN_DC err\n");
    }
    ret = gpio_direction_output(PIN_BL, 1);
    if (ret < 0)
    {
        printk("gpio_direction_output:PIN_BL err\n");
    }


}
void GC9A01_deinit_hard(void) {
    gpio_free(PIN_RST);
    gpio_free(PIN_DC);
    gpio_free(PIN_BL);
}
void GC9A01_set_reset(uint8_t val) {
    gpio_set_value(PIN_RST, val);
    // printk("PIN_RST:\%d (%d) \n", gpio_get_value(PIN_RST), val);

}
void GC9A01_set_data_command(uint8_t val) {
    gpio_set_value(PIN_DC, val);
    // printk("PIN_DC:\%d (%d) \n", gpio_get_value(PIN_DC), val);
}
void GC9A01_set_chip_select(uint8_t val) {
    gpio_set_value(PIN_CS, val);
    // printk("PIN_CS:\%d (%d) \n", gpio_get_value(PIN_CS), val);
}
void GC9A01_delay(uint16_t ms) {
    msleep(ms);
}

size_t GC9A01_spi_tx(uint8_t* data, size_t len) {
    size_t current_index = 0;
    uint32_t len_temp = 0;

    int ret = 0;
    while (current_index < len) {
        //发送
        len_temp = len - current_index;
        if (len_temp > TX_MAX_LEN)
        {
            len_temp = TX_MAX_LEN;
        }
        ret = spi_write(spi_screen_spi_device, (const void*)(current_index + data), len_temp);
        if (ret > 0)
        {
            //发送失败
            break;
        }

        current_index += len_temp;
    }
    return current_index;
}


// #include <linux/module.h>
// MODULE_LICENSE("GPL");


